using Concurso.Clases;
using Curriculum.Modelo.Clases;
using Utiles;

namespace ConcursoCV.UI.WebUserControls.Lookups
{
	using System;
	using System.Collections;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using Curriculum.Services;

	/// <summary>
	///		Summary description for AdministracionLookups.
	/// </summary>
	public class AdministracionLookups : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.DataGrid dtgJurados;
		protected System.Web.UI.WebControls.Button btnAceptar;
		protected System.Web.UI.WebControls.Button btnCancelar;
		protected System.Web.UI.WebControls.Panel pnlABM;
		protected System.Web.UI.WebControls.TextBox txtDescripcion;
		protected System.Web.UI.WebControls.Label lblCount;
		protected System.Web.UI.WebControls.Label lblDescAction;
		protected System.Web.UI.WebControls.Button btnNew;
		protected System.Web.UI.WebControls.Label lblScreenTitle;
		protected System.Web.UI.WebControls.Label lblListTitle;
		protected System.Web.UI.WebControls.Label lblLookupTypeTitle;

		private const string pidLookupType = "003";

		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!this.IsPostBack)
			{								
				InitializeVariables();
				this.LookupTypeDesc = Request.QueryString["type"];
				SetScreenTitle();
				FillDataGrid();	
			}
		}

		private void SetScreenTitle()
		{
			string screenTitle = string.Empty;
			string buttonTitle = string.Empty;
			switch(this.LookupTypeDesc.ToString())
			{
				case "INSTIT":
						screenTitle = "Instituciones";
						buttonTitle = "Nueva Institucion";
					break;
				case "DEPART":
						screenTitle = "Departamentos";
						buttonTitle = "Nuevo Departamento";
					break;
				case "AREA":
						screenTitle = "AREAS";
						buttonTitle = "Nueva Area";
					break;
				case "CARGO":
					screenTitle = "Cargos";
					buttonTitle = "Nuevo Cargo";
					break;
				default:
					throw new Exception("Verifique que los lookuptypes necesarios para ejecutar la aplicacion esten cargados");	
			}
			lblScreenTitle.Text = screenTitle;
			lblListTitle.Text = screenTitle;
			btnNew.Text = buttonTitle;
			lblLookupTypeTitle.Text = buttonTitle.Split(' ')[1];
		}

		private void InitializeVariables()
		{
			SortColumn = "Descripcion";
			SortDirection = true;			
		}

		private void FillDataGrid()
		{
			LookupTypeService service = new LookupTypeService();
			IList list = service.GetLookUpByDescType(Request.QueryString["type"]);

			((ArrayList)list).Sort(new GenericComparer(SortColumn,SortDirection));
			lblCount.Text = list.Count.ToString();
			dtgJurados.DataSource = list;
			try 
			{
				dtgJurados.DataBind();				
			}
			catch
			{
				dtgJurados.CurrentPageIndex=0;
				FillDataGrid();
			}
			list = null;
		}

		private void ABMPanelVisible(bool visible)
		{
			pnlABM.Visible = visible;
		}


		#region - Loads Methods -

		private void LoadLookup() 
		{
			LookupTypeService service = new LookupTypeService();
			Lookup lookup = service.ObtenerLookup(LookupId);
			this.LookupId = lookup.Id;
			txtDescripcion.Text = lookup.Descripcion;
		}

		#endregion - Loads Methods -
		
		private void Save()
		{
			// UPDATE
			if ( LookupId != null ) 
			{				
				UpdateLookup();
			}
			else
			{
				// CREATE
				AddLookup();
			}				
		}

		private void UpdateLookup()
		{
			LookupTypeService service = new LookupTypeService();
			Lookup lookup = service.ObtenerLookup(this.LookupId);
			lookup.Descripcion = txtDescripcion.Text;
			service.ModificarLookup(lookup);			
		}

		private void AddLookup()
		{
			LookupTypeService service = new LookupTypeService();
			service.GuardarNuevoLookUp(txtDescripcion.Text, this.LookupTypeDesc.ToString());
		}

		private void DeleteLookup() 
		{
			LookupTypeService service = new LookupTypeService();
			service.EliminarLookup(this.LookupId);
		}

		private void EnabledDisableControls(bool enabled) 
		{
			txtDescripcion.Enabled = enabled;
			btnNew.Enabled = enabled;
			btnAceptar.Enabled = enabled;
		}

		private void CleanControls() 
		{
			txtDescripcion.Text = string.Empty;
		}
		private void RedirectToLookupTypePage()
		{
			string url = "Default.aspx?pid="+ pidLookupType + "&type=" + this.LookupTypeDesc.ToString();
			this.Server.Transfer(url);
		}

		#region - properties -

		private object LookupTypeDesc
		{
			get{ return ViewState["lookupTypeDesc"]; }
			set{ ViewState["lookupTypeDesc"] = value; }
		}
		private object LookupId
		{
			get{ return ViewState["lookupId"]; }
			set{ ViewState["lookupId"] = value; }
		}

		#region - Sort Variables -

		public string SortColumn
		{
			get{ return (string)ViewState["SortColumn"];}
			set{ ViewState["SortColumn"] = value;}
		}
		public bool SortDirection
		{
			get{ return (bool)ViewState["SortDirection"];}
			set{ ViewState["SortDirection"] = value;}
		}

		#endregion - Sort Variables -

		#endregion - properties -

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dtgJurados.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dtgJurados_ItemCommand);
			this.dtgJurados.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dtgJurados_PageIndexChanged);
			this.dtgJurados.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dtgJurados_SortCommand);
			this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
			this.btnAceptar.Click += new System.EventHandler(this.btnAceptar_Click);
			this.btnCancelar.Click += new System.EventHandler(this.btnCancelar_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnNew_Click(object sender, System.EventArgs e)
		{			
			ABMPanelVisible(true);	
			lblDescAction.Text = "Agregar ";
			this.LookupId = null;
			CleanControls();					
		}

		private void btnCancelar_Click(object sender, System.EventArgs e)
		{
			this.LookupId = null;
			ABMPanelVisible(false);
			RedirectToLookupTypePage();
		}

		private void btnAceptar_Click(object sender, System.EventArgs e)
		{
			Save();
			RedirectToLookupTypePage();
		}

		private void dtgJurados_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if ( e.CommandName != "Page" ) 
			{				
				LookupId = e.Item.Cells[0].Text;		
				switch ( e.CommandName ) 
				{
					case "View":
							LoadLookup();
							EnabledDisableControls(false);
							lblDescAction.Text = "Ver ";
							ABMPanelVisible(true);
						break;

					case "Modify":
							LoadLookup();
							EnabledDisableControls(true);
							lblDescAction.Text = "Modificar ";
							ABMPanelVisible(true);
						break;
						
					case "Delete":
							DeleteLookup();
							FillDataGrid();							
							ABMPanelVisible(false);
						break;
				}		
			}		
		}


		private void dtgJurados_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			dtgJurados.CurrentPageIndex = e.NewPageIndex;
			FillDataGrid();
		}

		private void dtgJurados_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			//Si se hace click sobre ,la misma columna, cambia el orden
			if (SortColumn.ToString() == e.SortExpression.ToString())
				SortDirection = !SortDirection;
			
			SortColumn = e.SortExpression;
			FillDataGrid();		
		}
	}
}
